package org.box.metadata.shell.web.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.buffer.CircularFifoBuffer;
import org.box.metadata.shell.web.WebConsoleCallback;
import org.box.metadata.shell.web.WebShell;

public class CSSConsoleCallbackServlet extends ConsoleCallbackServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final static Logger LOG = Logger
			.getLogger(CSSConsoleCallbackServlet.class.getName());

	public CSSConsoleCallbackServlet(WebShell shell,
			ByteArrayOutputStream outContent, int bufferSize) {
		super(shell, outContent, bufferSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected WebConsoleCallback createCallback(HttpServletRequest req, CircularFifoBuffer buffer) {
    	if (LOG.isLoggable(Level.FINE)) 
    		LOG.fine("RequestedSessionIdValid: " + req.isRequestedSessionIdValid());
	
		HttpSession session = req.getSession(true);
		String sid = session != null ? session.getId() : null;
		String currentInput = shell.getCurrentInput();
		int li = getLastIndex(req, sid);
		
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("Session: " + sid + "; LI: " + li + "; currentInput: " + currentInput);		

		return new WebConsoleCallback(buffer, li, sid, currentInput != null);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		resp.setContentType("application/json; charset=utf-8");

    	if (LOG.isLoggable(Level.FINE)) 
    		LOG.fine("RequestedSessionIdValid: " + req.isRequestedSessionIdValid());
    	
		HttpSession session = req.getSession(true);
		String sid = session.getId();
		String cmd = req.getParameter("cmd");
		
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("Session: " + sid + "; cmd: " + cmd);		

		if (cmd != null && !cmd.trim().isEmpty())
			shell.submitInput(cmd, sid);
	}

}
